package util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;


public class HibernateUtil {

	private static Configuration configuration;
	private static SessionFactory sessionFactory;
	
	private static final String HIBERNATE_CFG_XML = "hibernate.cfg.xml";
	
	public static void setUp() {
		try {
			configuration = new AnnotationConfiguration();
			sessionFactory = configuration.configure(HIBERNATE_CFG_XML)
					.buildSessionFactory();
		} catch (Throwable ex) {
			throw new ExceptionInInitializerError(ex);
		}
	}
	
	//Criar se necessario.
	// ---------------------------------------------------------------------
	
	public static void beginTransaction() {
		Transaction tx = (Transaction) sessionFactory.getCurrentSession()
				.beginTransaction();
		try {
			if (tx == null) {
				tx = getSession().beginTransaction();
			}
		} catch (HibernateException ex) {
			System.err.println("beginTransaction" + ex.getMessage());
		}
	}

	public static void commitTransaction() {
		Transaction tx = (Transaction) sessionFactory.getCurrentSession()
				.getTransaction();
		try {
			if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
				tx.commit();
			}
		} catch (HibernateException ex) {
			rollbackTransaction();
		} finally {
			closeSession();
		}
	}

	public static void rollbackTransaction() {
		Transaction tx = (Transaction) sessionFactory.getCurrentSession()
				.getTransaction();
		try {
			if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
				tx.rollback();
			}
		} catch (HibernateException ex) {
		}
	}

	public static void closeSession() {
		try {
			Session session = (Session) sessionFactory.getCurrentSession();
			if (session != null && session.isOpen()) {
				session.close();
			}
		} catch (HibernateException ex) {
		}
	}

	public static void rollbackAndCloseSession() {
		rollbackTransaction();
		closeSession();
	}

	public static Session getSession() {
		Session session = (Session) sessionFactory.getCurrentSession();
		try {
			if (session == null || !session.isOpen()) {
				session = getSessionFactory().openSession();
			}
		} catch (HibernateException ex) {
		}
		return session;
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static Configuration getConfiguration() {
		return configuration;
	}

	public static Session getCurrentSession() throws HibernateException {
		return sessionFactory.getCurrentSession();
	}
}